#!/bin/bash

######################################################
# file : editdiary
#   This script allows the user to edit notes for any chosen date in the diary
#
# Author : Anil Kainikara (anilkumar911@gmail.com)
#
# This code is licenced under the GPL.
#
######################################################


export day=
export month=
export year=

export powerdate=

export diarydb="${HOME}/.local/share/powerdiary2.db"
export tmp_folder="/tmp/diary/$USER/$$"
export chdmn_file="/tmp/change_lock"

if [[ ! -a $diarydb ]]
then
  sqlite3 ${diarydb} << EOFL
  CREATE TABLE entries (date TEXT, content TEXT, PRIMARY KEY (date));
EOFL

fi

if [[ ! -a ~/.local/share/powerdiary2.properties ]]
then
  echo "Google calendar account has not been configured"
  echo -n "would you like to do it now [Y/n] : "
  read choice
  if [[ $choice == "Y" || $choice == "y" ]]
  then
    cp /opt/powerdiary2/lib/powerdiary2.properties ~/.local/share/powerdiary2.properties
    vi ~/.local/share/powerdiary2.properties
  fi
fi

crontab -l | grep "diary_gcal.sh" > /dev/null
if [[ $? -ne 0 ]]
then
  crontab -l > /tmp/crontab.tmp
  echo '*/10 * * *    *     /opt/powerdiary2/bin/diary_gcal.sh' >> /tmp/crontab.tmp
  crontab /tmp/crontab.tmp
  #rm /tmp/crontab.tmp
fi

if [[ ${DIARY_EDITOR}"NULL" == "NULL" ]]
then
  export DIARY_EDITOR=vi
fi

DATE_Y2H=`date +"%Y-%m-%d"`

usage()
{
  echo "Usage : editdiary dd/mm/yyyy"
}

# watches the file for changes and updates the database while
# the entry is being edted.
changedaemon()
{
  watchdate=$1;
  action=$2
  tmpfiledate=$(echo $watchdate | sed -e 's/\//_/g')
  while [[ true ]]
  do
    diff ${tmp_folder}/diary${tmpfiledate}.content ${tmp_folder}/diary${tmpfiledate}.content.new >/dev/null 2>&1
    if [[ $? -ne 0 ]]
    then
      touch ${chdmn_file} # entering critical code.
      #update the db with new content.
      content=`cat ${tmp_folder}/diary${DATE_Y2H}.content.new| sed -e"s/'/''/g"`
      cp ${tmp_folder}/diary${tmpfiledate}.content.new ${tmp_folder}/diary${tmpfiledate}.content
      if [[ $action == "edit" ]]
      then
        #update existing entry
        sqlite3 $diarydb "update entries set content='$content' where date='$watchdate';"
        echo "$0: Updated date($watchdate) content $content">> /tmp/powerdiary.log 2>&1
      else
        # create(insert) a new entry for this date
        sqlite3 $diarydb "insert into entries values ('$watchdate', '$content');"
        action="edit"
        echo "$0: added for date($watchdate) content $content">> /tmp/powerdiary.log 2>&1
      fi
      rm ${chdmn_file} #Leaving critical code
    fi
    sleep 3
  done
}

parsedate()
{
  date=$1
  if [[ -z $date ]]
  then
    #set -e
    date=`dialog --stdout --calendar "Choose Date" 6 15`
    clear
    #set +e
    if [[ -z $date ]]
    then
      date=`date +%d/%m/%Y`;
    fi
  fi
  day=`echo $date | cut -d'/' -f1`
  month=`echo $date | cut -d'/' -f2`
  year=`echo $date | cut -d'/' -f3`
}

cleanup()
{
  rm -f ${tmp_folder}/diary${DATE_Y2H}.content
  #rm -f ${tmp_folder}/diary${DATE_Y2H}.content.new
}

main()
{
  l_date=$1
  mkdir -p ${tmp_folder};
  while [[ true ]]
  do
    parsedate $l_date
    powerdate=`printf "%d/%.2s/%.2s" "$year" "$month" "$day"`
    endaction="create"
    DATE_Y2H=`echo $powerdate | sed -e 's/\//_/g'`
    sqlite3 $diarydb "select content from entries where date='$powerdate';" > ${tmp_folder}/diary${DATE_Y2H}.content
    if [[ -s ${tmp_folder}/diary${DATE_Y2H}.content ]]
    then
       endaction="edit"
    fi

    cp ${tmp_folder}/diary${DATE_Y2H}.content ${tmp_folder}/diary${DATE_Y2H}.content.new
    changedaemon $powerdate $endaction &
    ${DIARY_EDITOR} ${tmp_folder}/diary${DATE_Y2H}.content.new

    # Stop the change daemon.
    ## find the pid.
    change_pid=`jobs -l | awk '{print $2}'`
    while [[ -a $chdmn_file ]]
    do
      sleep 1
    done
    kill -9 $change_pid # kill the daemon

    diff ${tmp_folder}/diary${DATE_Y2H}.content ${tmp_folder}/diary${DATE_Y2H}.content.new 2>&1>/dev/null
    if [[ $? -eq 0 ]]
    then
       echo no change
    else
      content=`cat ${tmp_folder}/diary${DATE_Y2H}.content.new| sed -e"s/'/''/g"`

      if [[ $endaction == "edit" ]]
      then
        echo update
        set -e
        sqlite3 $diarydb "update entries set content='$content' where date='$powerdate';"
        echo "$0: Updated date($powerdate) content $content">> /tmp/powerdiary.log 2>&1
        set +e
      else
        echo create
        set -e
        sqlite3 $diarydb "insert into entries values ('$powerdate', '$content');"
        echo "$0: added for date($powerdate) content $content">> /tmp/powerdiary.log 2>&1
        set +e
      fi
      cleanup
    fi
    l_date=""
    set -e
    date=`dialog  --stdout --yesno "Continue" 0 0`
    set +e
  done
}

main $@
